﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Utilities;

namespace ManageTicket.Tools
{
    public partial class frmInvoiceOther : frmBase
    {
        #region Contructor
        public frmInvoiceOther()
        {
            InitializeComponent();
        }
        #endregion

        #region Variable
        ManageTicket.Library.Control.ExecuteControl exeCtrl;

        //permission
        bool bAdd = false;
        bool bEdit = false;
        bool bDelete = false;
        bool bCancel = false;
        bool bSave = false;
        bool bFunction = false;
        bool bView = false;
        bool bFind = false;
        bool bExport = false;
        bool bSendmail = false;
        bool bPrint = false;

        clsMethod4All objMethod = new clsMethod4All();
        ManageTicket.Library.Common.CommonFunction clsCommonFunc = new ManageTicket.Library.Common.CommonFunction();
        private Business.InvoiceOther boInvoice = new Business.InvoiceOther();
        private Business.Employee boEmployee = new Business.Employee();
        private Business.CodeType boCodeType = new Business.CodeType();
        string sModel = ""; //Store AND or UPDATE status
        private const string ADD_MODEL = "ADD";
        private const string UPDATE_MODEL = "UPDATE";
        #endregion

        #region Event
        private void frmInvoiceOther_Load(object sender, EventArgs e)
        {
            //execute control
            exeCtrl = new ManageTicket.Library.Control.ExecuteControl();
            exeCtrl.Dock = DockStyle.Fill;
            exeCtrl.lblDescription.Text = "Cập nhật hóa đơn";
            pnlExe.Controls.Add(exeCtrl);

            //permission
            clsCommonFunc.GetPermission(ref bAdd, ref bEdit, ref bDelete, ref bCancel, ref bSave, ref bFunction, ref bView, ref bFind, ref bExport, ref bSendmail, ref bPrint, frmMain.CurrentUser.UserId, "FORM_08");

            clsCommonFunc.GetListCodeType(cboCurrency, "CUR");
            clsCommonFunc.GetListCodeType(cboPaymentForm, "PF");
            clsCommonFunc.GetListCodeType(cboBank, "BANK");
            cboKindOfInvoice.SelectedIndex = -1;
            cboCurrency.SelectedIndex = -1;
            cboPaymentForm.SelectedIndex = -1;
            cboPaymentForm_SelectedIndexChanged(null, null);

            objMethod.ClearText(new Control[] { txtInvoiceNo, txtMoney, txtExchange, txtMoneyVND, txtCashierId, txtCashierName, txtReceiverId, txtReceiverName, txtRemark });

            objMethod.en_dis_control(new Control[] { grpListInvoice }, new Control[] { grpDetail });
            LoadStatusOnce();
            LoadStatus(true, false, false, false, false);

            //default date value
            dtpDateFrom.Value = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1, 0, 0, 0);
            dtpDateTo.Value = new DateTime(DateTime.Now.Year, DateTime.Now.Month, objMethod.GetEndDayOfMonth(DateTime.Now.Month, DateTime.Now.Year), 23, 59, 59);
        }

        private void lvwInvoice_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lvwInvoice.SelectedItems.Count > 0)
            {
                FillData(lvwInvoice.SelectedItems[0].Text);
                LoadStatus(true, true, true, false, false);
            }
            else
            {
                LoadStatus(true, false, false, false, false);
                objMethod.ClearText(new Control[] { txtInvoiceNo, txtMoney, txtExchange, txtMoneyVND, txtCashierId, txtCashierName, txtReceiverId, txtReceiverName, txtRemark });
                cboKindOfInvoice.SelectedIndex = -1;
                cboCurrency.SelectedIndex = -1;
                cboPaymentForm.SelectedIndex = -1;
                cboPaymentForm_SelectedIndexChanged(null, null);
            }
        }

        private void dtpDateOfInvoice_ValueChanged(object sender, EventArgs e)
        {
            if (sModel == ADD_MODEL)
                txtInvoiceNo.Text = "A" + dtpDateOfInvoice.Value.ToString("yyyyMMdd") + clsCommonFunc.RuleNumber5(boInvoice.GetMaxID("A" + dtpDateOfInvoice.Value.ToString("yyyyMMdd")) + 1);
        }

        private void cboCurrency_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboCurrency.SelectedIndex >= 0)
            {
                if (cboCurrency.SelectedValue.ToString().ToUpper() == "CUR_1")
                {
                    txtExchange.Text = "1";
                    Calculate();
                }
            }
        }

        private void cboPaymentForm_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (cboPaymentForm.SelectedIndex != -1)
                {
                    if (cboPaymentForm.SelectedValue.ToString() == "PF_1")
                    {
                        cboBank.SelectedIndex = -1;
                        cboBank.Enabled = false;
                    }
                    else
                    {
                        cboBank.Enabled = true;
                        if (cboBank.Items.Count > 0)
                        {
                            cboBank.SelectedIndex = 0;
                            cboBank.Focus();
                        }
                    }
                }
                else
                {
                    cboBank.SelectedIndex = -1;
                    cboBank.Enabled = false;
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void txtMoney_KeyPress(object sender, KeyPressEventArgs e)
        {
            objMethod.InputNumber(e, txtMoney.Text);
        }

        private void txtMoney_Leave(object sender, EventArgs e)
        {
            Calculate();
        }

        private void txtExchange_KeyPress(object sender, KeyPressEventArgs e)
        {
            objMethod.InputNumber(e, txtExchange.Text);
        }

        private void txtExchange_Leave(object sender, EventArgs e)
        {
            Calculate();
        }

        private void txtCashierId_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                DataObjects.Employee oCus = boEmployee.GetObjectByPK(txtCashierId.Text);
                if (oCus != null)
                {
                    txtCashierName.Text = oCus.LastName + " " + oCus.FirstName;
                    txtCashierName.Focus();
                }
            }
        }

        private void txtReceiverId_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                DataObjects.Employee oCus = boEmployee.GetObjectByPK(txtReceiverId.Text);
                if (oCus != null)
                {
                    txtReceiverName.Text = oCus.LastName + " " + oCus.FirstName;
                    txtReceiverName.Focus();
                }
            }
        }
        
        private void dtpDateFrom_ValueChanged(object sender, EventArgs e)
        {
            GetListInvoice(dtpDateFrom.Value, dtpDateTo.Value);
        }

        private void dtpDateTo_ValueChanged(object sender, EventArgs e)
        {
            GetListInvoice(dtpDateFrom.Value, dtpDateTo.Value);
        }
        #endregion

        #region Execute
        public override void Add()
        {
            objMethod.ClearText(new Control[] { txtInvoiceNo, txtMoney, txtExchange, txtMoneyVND, txtCashierId, txtCashierName, txtReceiverId, txtReceiverName, txtRemark });
            LoadStatus(false, false, false, true, true);
            objMethod.en_dis_control(new Control[] { grpDetail, txtInvoiceNo }, new Control[] { grpListInvoice });

            dtpDateOfInvoice.Value = DateTime.Now;
            txtInvoiceNo.Text = "A" + dtpDateOfInvoice.Value.ToString("yyyyMMdd") + clsCommonFunc.RuleNumber5(boInvoice.GetMaxID("A" + dtpDateOfInvoice.Value.ToString("yyyyMMdd")) + 1);

            if (cboPaymentForm.SelectedIndex >= 0)
                cboPaymentForm.SelectedIndex = 0;
            cboPaymentForm_SelectedIndexChanged(null, null);

            txtCashierId.Text = frmMain.CurrentUser.EmployeeId;
            DataObjects.Employee oCus = boEmployee.GetObjectByPK(txtCashierId.Text);
            if (oCus != null)
            {
                txtCashierName.Text = oCus.LastName + " " + oCus.FirstName;
            }

            dtpDateOfInvoice.Focus();
            sModel = ADD_MODEL;
        }

        public override void Edit()
        {
            if (lvwInvoice.SelectedItems.Count <= 0)
                return;
            LoadStatus(false, false, false, true, true);
            objMethod.en_dis_control(new Control[] { grpDetail, txtInvoiceNo }, new Control[] { grpListInvoice, txtInvoiceNo });

            dtpDateOfInvoice.Focus();
            sModel = UPDATE_MODEL;
        }

        public override void Delete()
        {
            try
            {
                if (txtInvoiceNo.Text == "")
                    return;

                if (MessageBox.Show("Bạn có thực sự muốn xóa?", "Aquarius", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    //Check Existing in table
                    //if (this.CheckExitToDelete(oDept.DEPT_CODE)) {
                    //    MessageBox.Show(".", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    //    return;
                    //}

                    //delete
                    boInvoice.DeleteByPK(txtInvoiceNo.Text);

                    MessageBox.Show("Xóa hóa đơn thành công.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Cancel();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public override void Cancel()
        {
            objMethod.ClearText(new Control[] { txtInvoiceNo, txtMoney, txtExchange, txtMoneyVND, txtCashierId, txtCashierName, txtReceiverId, txtReceiverName, txtRemark });
            GetListInvoice(dtpDateFrom.Value, dtpDateTo.Value);
            if (lvwInvoice.Items.Count > 0)
            {
                lvwInvoice.Items[0].Selected = true;
            }
            else
            {
                LoadStatus(true, false, false, false, false);
            }
            objMethod.en_dis_control(new Control[] { grpListInvoice }, new Control[] { grpDetail });

            sModel = "";
        }

        public override void Save()
        {
            if (CheckValid())
            {
                try
                {
                    DataObjects.InvoiceOther oInvoice = new DataObjects.InvoiceOther();
                    oInvoice.InvoiceNo = txtInvoiceNo.Text;
                    oInvoice.DateOfInvoice = dtpDateOfInvoice.Value;
                    oInvoice.KindOfInvoice = cboKindOfInvoice.Text;
                    oInvoice.Money = txtMoney.Text != "" ? double.Parse(txtMoney.Text) : 0;
                    oInvoice.Currency = cboCurrency.SelectedValue.ToString();
                    oInvoice.Exchange = txtExchange.Text != "" ? double.Parse(txtExchange.Text) : 0;
                    oInvoice.PaymentForm = cboPaymentForm.SelectedValue.ToString();
                    if (cboBank.SelectedIndex >= 0)
                        oInvoice.Bank = cboBank.SelectedValue.ToString();
                    oInvoice.Cashier = txtCashierId.Text;
                    oInvoice.Receiver = txtReceiverId.Text;
                    oInvoice.Remark = txtRemark.Text;

                    if (sModel == ADD_MODEL)
                    {
                        //insert
                        if (CheckIsExist(oInvoice.InvoiceNo))
                        {
                            MessageBox.Show("Số hóa đơn đã tồn tại.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            txtInvoiceNo.Focus();
                            return;
                        }
                        boInvoice.Insert(oInvoice);
                    }
                    else if (sModel == UPDATE_MODEL)
                    {
                        boInvoice.Update(oInvoice);
                    }
                    MessageBox.Show("Cập nhật hóa đơn thành công.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Cancel();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message + Environment.NewLine + "Không thể cập nhật hóa đơn.", "Aquarius Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        #endregion

        #region Method

        private void LoadStatusOnce()
        {
            exeCtrl.btnView.Enabled = false;
            exeCtrl.btnExport.Enabled = false;
            exeCtrl.btnSendmail.Enabled = false;
            exeCtrl.btnPrint.Enabled = false;
            exeCtrl.btnFunction.Enabled = false;
            exeCtrl.btnFind.Enabled = false;

            exeCtrl.btnView.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnExport.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnSendmail.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnPrint.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnFunction.BackColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnFind.ButtonColor = Color.FromArgb(171, 171, 171);

            exeCtrl.btnView.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnExport.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnSendmail.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnPrint.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnFunction.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnFind.ForeColor = Color.FromArgb(241, 244, 251);
        }

        private void LoadStatus(bool blAdd, bool blEdit, bool blDelete, bool blCancel, bool blSave)
        {
            exeCtrl.btnAdd.Enabled = blAdd & bAdd;
            exeCtrl.btnEdit.Enabled = blEdit & bEdit;
            exeCtrl.btnDelete.Enabled = blDelete & bDelete;
            exeCtrl.btnCancel.Enabled = blCancel & bCancel;
            exeCtrl.btnSave.Enabled = blSave & bSave;

            exeCtrl.btnAdd.ButtonColor = exeCtrl.btnAdd.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);
            exeCtrl.btnEdit.ButtonColor = exeCtrl.btnEdit.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);
            exeCtrl.btnDelete.ButtonColor = exeCtrl.btnDelete.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);
            exeCtrl.btnCancel.ButtonColor = exeCtrl.btnCancel.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);
            exeCtrl.btnSave.ButtonColor = exeCtrl.btnSave.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);

            exeCtrl.btnAdd.ForeColor = exeCtrl.btnAdd.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
            exeCtrl.btnEdit.ForeColor = exeCtrl.btnEdit.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
            exeCtrl.btnDelete.ForeColor = exeCtrl.btnDelete.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
            exeCtrl.btnCancel.ForeColor = exeCtrl.btnCancel.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
            exeCtrl.btnSave.ForeColor = exeCtrl.btnSave.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
        }

        private void GetListInvoice(DateTime datefrom, DateTime dateto)
        {
            try
            {
                lvwInvoice.Items.Clear();
                ArrayList arr = boInvoice.GetListByDate(datefrom, dateto);
                if (arr.Count > 0)
                {
                    ListViewItem item;
                    DataObjects.CodeType oCodeType;
                    foreach (DataObjects.InvoiceOther oInv in arr)
                    {
                        item = new ListViewItem();
                        item.Text = oInv.InvoiceNo;
                        item.SubItems.Add(oInv.DateOfInvoice.Value.ToString("dd/MM/yyyy hh:mm tt"));
                        item.SubItems.Add(oInv.KindOfInvoice);
                        item.SubItems.Add(objMethod.FormatCurency(oInv.Money.ToString()));
                        oCodeType = boCodeType.GetObjectByPK(oInv.Currency);
                        if (oCodeType != null)
                            item.SubItems.Add(oCodeType.CodeTypeName);
                        else
                            item.SubItems.Add("");
                        oCodeType = null;
                        oCodeType = boCodeType.GetObjectByPK(oInv.PaymentForm);
                        if (oCodeType != null)
                            item.SubItems.Add(oCodeType.CodeTypeName);
                        else
                            item.SubItems.Add("");
                        oCodeType = null;
                        item.SubItems.Add(oInv.Remark);
                        lvwInvoice.Items.Add(item);
                    }

                    if (lvwInvoice.Items.Count > 0)
                    {
                        lvwInvoice.Items[0].Selected = true;
                    }
                }
                else
                {
                    objMethod.ClearText(new Control[] { txtInvoiceNo, txtMoney, txtExchange, txtMoneyVND, txtCashierId, txtCashierName, txtReceiverId, txtReceiverName, txtRemark });
                    cboKindOfInvoice.SelectedIndex = -1;
                    cboCurrency.SelectedIndex = -1;
                    cboPaymentForm.SelectedIndex = -1;
                    cboPaymentForm_SelectedIndexChanged(null, null);
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void Calculate()
        {
            try
            {
                double money = 0;
                double exchange = 0;
                double moneyvnd = 0;

                try { money = txtMoney.Text != "" ? double.Parse(txtMoney.Text) : 0; }
                catch { }

                try
                {
                    if (cboCurrency.SelectedValue.ToString().ToUpper() == "CUR_1")
                    {
                        exchange = 1;
                    }
                    else
                    {
                        exchange = txtExchange.Text != "" ? double.Parse(txtExchange.Text) : 0;
                    }
                }
                catch { }
                moneyvnd = money * exchange;

                //display
                txtMoney.Text = objMethod.FormatCurency(money.ToString());
                txtExchange.Text = objMethod.FormatCurency(exchange.ToString());
                txtMoneyVND.Text = objMethod.FormatCurency(moneyvnd.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void FillData(string invoice_no)
        {
            DataObjects.InvoiceOther oInv = boInvoice.GetObjectByPK(invoice_no);
            DataObjects.Employee oEmp;
            if (oInv != null)
            {
                txtInvoiceNo.Text = oInv.InvoiceNo;
                dtpDateOfInvoice.Value = oInv.DateOfInvoice.Value;
                cboKindOfInvoice.Text = oInv.KindOfInvoice;
                txtMoney.Text = objMethod.FormatCurency(oInv.Money.ToString());
                cboCurrency.SelectedValue = oInv.Currency;
                txtExchange.Text = objMethod.FormatCurency(oInv.Exchange.ToString());
                Calculate();
                cboPaymentForm.SelectedValue = oInv.PaymentForm;
                if (oInv.Bank != null && oInv.Bank != "")
                    cboBank.SelectedValue = oInv.Bank;
                else
                    cboBank.SelectedIndex = -1;
                txtCashierId.Text = oInv.Cashier;
                oEmp = boEmployee.GetObjectByPK(oInv.Cashier);
                if (oEmp != null)
                    txtCashierName.Text = oEmp.LastName + " " + oEmp.FirstName;
                txtReceiverId.Text = oInv.Receiver;
                oEmp = null;
                oEmp = boEmployee.GetObjectByPK(oInv.Receiver);
                if (oEmp != null)
                    txtReceiverName.Text = oEmp.LastName + " " + oEmp.FirstName;
                txtRemark.Text = oInv.Remark;
            }
        }

        private bool CheckValid()
        {
            if (txtInvoiceNo.Text.Trim().Length == 0)
            {
                MessageBox.Show("Vui lòng nhập số hóa đơn.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtInvoiceNo.Focus();
                return false;
            }
            else if (!objMethod.CheckSpecialCharacter(txtInvoiceNo.Text))
            {
                MessageBox.Show("Số hóa đơn không được nhập các ký tự đặc biệt.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtInvoiceNo.Focus();
                return false;
            }

            if (cboKindOfInvoice.Text.Trim().Length == 0)
            {
                MessageBox.Show("Vui lòng chọn thu/chi.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                cboKindOfInvoice.Focus();
                return false;
            }

            if (txtMoney.Text.Trim().Length == 0)
            {
                MessageBox.Show("Vui lòng nhập số tiền.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtMoney.Focus();
                return false;
            }

            if (cboCurrency.Text.Trim().Length == 0)
            {
                MessageBox.Show("Vui lòng chọn loại tiền tệ.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                cboCurrency.Focus();
                return false;
            }

            if (cboPaymentForm.Text.Trim().Length == 0)
            {
                MessageBox.Show("Vui lòng chọn hình thức thanh toán.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                cboPaymentForm.Focus();
                return false;
            }

            if (txtCashierId.Text.Trim().Length == 0)
            {
                MessageBox.Show("Vui lòng chọn người lập.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtCashierId.Focus();
                return false;
            }
            else
            {
                DataObjects.Employee oEmp = boEmployee.GetObjectByPK(txtCashierId.Text);
                if (oEmp == null)
                {
                    MessageBox.Show("Nhân viên không tồn tại.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtCashierId.Focus();
                    return false;
                }
            }

            if (txtReceiverId.Text.Trim().Length == 0)
            {
                MessageBox.Show("Vui lòng chọn người nhận.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtReceiverId.Focus();
                return false;
            }
            else
            {
                DataObjects.Employee oEmp = boEmployee.GetObjectByPK(txtReceiverId.Text);
                if (oEmp == null)
                {
                    MessageBox.Show("Nhân viên không tồn tại.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtReceiverId.Focus();
                    return false;
                }
            }

            return true;
        }

        private bool CheckIsExist(string invoice_no)
        {
            DataObjects.InvoiceOther oInvoice = boInvoice.GetObjectByPK(invoice_no);
            if (oInvoice != null)
            {
                return true;
            }
            return false;
        }
        #endregion
  
    }
}
